import BaseAction from '@/components/base/BaseAction';
import BaseButton from '@/components/base/BaseButton';
import { useModal } from '@/components/base/BaseModal';
import BasePageFrame from '@/components/base/BasePageFrame';
import BaseSearch from '@/components/base/BaseSearch';
import BaseSelect from '@/components/base/BaseSelect/index';
import BaseTable from '@/components/base/BaseTable';
import { useRequest } from '@/utils/request';
import {
  ApiOutlined,
  DeleteOutlined,
  EditOutlined,
  ExportOutlined,
  ImportOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import { Space } from 'antd';
import { useCallback, useMemo, useRef, useState } from 'react';
import { getClassList } from '../ClassInfo/api';
import { StudentModel } from '../data';
import { getMajorList } from '../MajorInfo/api';
import { deleteStudent, delStudentInfo, exportStudent, getStudentList } from './api';
import ImportModal from './modals/ImportModal';
import InfoModal from './modals/InfoModal';
import SyncUserModal from './modals/SyncUserModal';

const StudentInfo = () => {
  const tableRef = useRef<ActionType>();
  const infoModal = useModal(InfoModal, {
    onSuccess() {
      tableRef.current?.reload();
    }
  });
  const importModal = useModal(ImportModal, {
    onSuccess() {
      const reloadAndRest = tableRef.current?.reloadAndRest;
      reloadAndRest && reloadAndRest();
    }
  });
  const [selectKeys, setSelectKeys] = useState<string[]>([]);
  const syncUserModal = useModal(SyncUserModal, {
    onSuccess() {
      setSelectKeys([]);
    }
  });

  const [searchInfo, setSearchInfo] = useState<{
    filter?: string;
    majorId?: string;
    classId?: string;
  }>({});
  const setSearch = useCallback(
    (v: Partial<typeof searchInfo>) => {
      setSelectKeys([]);
      setSearchInfo({ ...searchInfo, ...v });
    },
    [searchInfo, setSearchInfo, setSelectKeys]
  );
  const del = useRequest(delStudentInfo, {
    manual: true,
    fetchKey: (id) => id,
    onSuccess() {
      setSelectKeys([]);
      tableRef.current?.reload();
    }
  });
  const delStudent = useRequest(deleteStudent, {
    manual: true,
    onSuccess() {
      tableRef.current?.reload();
      setSelectKeys([]);
    }
  });
  const toolbar = useMemo(
    () => [
      <BaseSelect
        request={getMajorList}
        placeholder='请选择学生专业'
        defaultValue={searchInfo.majorId}
        allowClear
        style={{ width: 150 }}
        fieldNames={{ label: 'majorName', value: 'id' }}
        onChange={(v) => {
          setSearch({ majorId: v, classId: undefined });
        }}
      />,
      <BaseSelect
        request={getClassList}
        disabled={searchInfo.majorId === '' || searchInfo.majorId === undefined}
        placeholder='请选择学生班级'
        allowClear
        style={{ width: 150 }}
        params={{ majorId: searchInfo.majorId }}
        fieldNames={{ label: 'className', value: 'id' }}
        value={searchInfo.classId}
        onChange={(v) => {
          setSearch({ classId: v });
        }}
      />,
      <BaseSearch
        style={{ width: 280 }}
        placeholder='请输入学号/学生姓名进行搜索'
        defaultValue={searchInfo.filter}
        onChange={(v) => setSearch({ filter: v })}
      />
    ],
    [searchInfo, setSearch]
  );
  return (
    <BasePageFrame>
      <BaseTable
        actionRef={tableRef}
        headerTitle={
          <Space>
            <BaseButton
              type='primary'
              icon={<PlusOutlined />}
              onClick={() => {
                infoModal.load({});
              }}
              code='create'
            >
              新增
            </BaseButton>
            <BaseButton
              icon={<ImportOutlined />}
              code='importExport'
              onClick={() => {
                importModal.load({});
              }}
            >
              导入数据
            </BaseButton>
          </Space>
        }
        rowKey='id'
        toolBarRender={() => toolbar}
        tableAlertOptionRender={() => (
          <Space size={8}>
            <BaseButton
              type='link'
              icon={<ExportOutlined />}
              code='importExport'
              title='导出数据'
              onClick={() => {
                exportStudent({
                  majorId: searchInfo.majorId,
                  classId: searchInfo.classId,
                  studentIds: selectKeys as string[]
                });
              }}
            >
              导出数据
            </BaseButton>
            <BaseButton
              type='link'
              disabled={selectKeys.length === 0}
              icon={<ApiOutlined />}
              title='用户同步'
              code='sync'
              onClick={() => {
                syncUserModal.load({ idList: selectKeys });
              }}
            >
              用户同步
            </BaseButton>
            <BaseButton
              type='link'
              disabled={selectKeys.length === 0}
              danger
              icon={<DeleteOutlined />}
              code='delete'
              title='批量删除'
              loading={delStudent.loading}
              onClick={() => {
                delStudent.run(selectKeys);
              }}
            >
              批量删除
            </BaseButton>
          </Space>
        )}
        request={getStudentList}
        params={searchInfo}
        rowSelection={{
          alwaysShowAlert: true,
          preserveSelectedRowKeys: true,
          selectedRowKeys: selectKeys,
          onChange: (keys) => {
            setSelectKeys(keys as string[]);
          }
        }}
        columns={
          [
            {
              dataIndex: 'studentId',
              title: '学号'
            },
            {
              dataIndex: 'name',
              title: '姓名'
            },
            {
              dataIndex: 'majorName',
              title: '专业'
            },
            {
              dataIndex: 'className',
              title: '班级'
            },
            {
              dataIndex: 'remarks',
              title: '备注'
            },
            {
              dataIndex: '',
              title: '操作',
              fixed: 'right',
              render(text, record) {
                return (
                  <Space>
                    <BaseAction
                      color='green'
                      icon={<EditOutlined />}
                      title='编辑'
                      code='edit'
                      onClick={() => {
                        infoModal.load({ data: record });
                      }}
                    />
                    <BaseAction
                      color='red'
                      icon={<DeleteOutlined />}
                      title='删除'
                      code='delete'
                      loading={del.fetches[record.id]?.loading}
                      onClick={() => {
                        del.run(record.id);
                      }}
                    />
                  </Space>
                );
              }
            }
          ] as ProColumns<StudentModel>[]
        }
      />
    </BasePageFrame>
  );
};

export default StudentInfo;
